<template>
  <xdh-dialog-form
    class="select-tree-dialog"
    :closed.sync="dialogClosed"
    :title="title"
    :width="width"
    maxHeight="550px"
    @open="openHandler"
    @close="closeHandler"
    :onUpdate="updateHandler"
    :mode="'update'">
    <el-input
      class="select-tree-dialog__filter"
      :placeholder="filterPlaceholder"
      v-model.lazy="filterText"
      size="mini">
    </el-input>

    <el-tree
      v-loading="treeLoading"
      class="select-tree-dialog__tree"
      :data="data"
      :props="props"
      :node-key="nodeKey"
      :default-expanded-keys="defaultExpandedKeys||[]"
      :filter-node-method="filterNode"
      :show-checkbox="multiSelect"
      :highlight-current="!multiSelect"
      :check-strictly="checkStrictly"
      @check-change="handleCheckChange"
      @current-change="currentChange"
      ref="tree">
    </el-tree>
  </xdh-dialog-form>
</template>

<script>
  import XdhDialogForm from '../widgets/xdh-dialog-form'
  import {treeFetchParent} from '../helper/tree'

  export default {
    name: 'SelectTreeDialog',
    components: {
      XdhDialogForm
    },
    data() {
      return {
        filterText: '',
        currentCheckedNodes: [],
        dialogClosed: this.closed,
        defaultExpandedKeys: []
      };
    },
    props: {
      // 树操作标题
      title: {
        type: String,
        default: ''
      },
      // 树结构数据
      data: {
        type: Array,
        default() {
          return [];
        }
      },
      // 是否关闭，支持双向绑定修饰符
      closed: {
        type: Boolean,
        default: true
      },
      // 对话框宽度
      width: {
        type: String,
        default: '450px'
      },
      // 树结构Prop
      props: {
        type: Object,
        default() {
          return {
            children: 'children',
            label: 'label'
          };
        }
      },
      // tree node-key
      nodeKey: {
        type: String,
        default: 'id'
      },
      // 树是否遵循父子不互相关联
      checkStrictly: {
        type: Boolean,
        default: false
      },
      // 树结构数据过滤只保留上级
      isFetchParent: {
        type: Boolean,
        default: true
      },
      filterPlaceholder: {
        type: String,
        default: '输入关键字进行过滤'
      },
      value: {
        type: Array,
        default() {
          return [];
        }
      },
      // 是否多选 默认多选
      multiSelect: {
        type: Boolean,
        default: true
      },
      // 树loading
      treeLoading: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      dialogClosed(val) {
        this.$emit('update:closed', val);
      },
      closed(val) {
        this.dialogClosed = val;
      },
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      value(val) {
        this.defaultValue(val)
      }
    },
    methods: {
      filterNode(value, data) {
        if (!value) return true;
        return data[this.props.label].indexOf(value) !== -1;
      },
      updateHandler(model) {
        this.$emit('submit', this.currentCheckedNodes);
        return Promise.resolve();
      },
      currentChange(data, node) {
        if (!this.multiSelect) {
          let cKey = this.$refs.tree.getCurrentKey()
          let cNode = this.$refs.tree.getCurrentNode()
          this.currentCheckedNodes = [
            {
              keys: cKey ? [cKey] : [],
              nodes: cNode ? [cNode] : []
            }
          ]
        }
      },
      handleCheckChange(data, node, current) {
        clearTimeout(this.__timer)
        this.__timer = setTimeout(() => {
          this.checkChange(data, node, current)
        }, 200)
      },
      checkChange(data, node, current) {
        this.currentCheckedNodes = [
          {
            keys: this.$refs.tree.getCheckedKeys(),
            nodes: this.$refs.tree.getCheckedNodes()
          }
        ];
        if (this.isFetchParent) {
          this.currentCheckedNodes[0].keys = [];
          this.currentCheckedNodes[0].nodes = treeFetchParent(
            this.currentCheckedNodes[0].nodes
          ).map(rn => {
            this.currentCheckedNodes[0].keys.push(rn[this.nodeKey]);
            return rn;
          });
        }
        this.$emit('input', this.currentCheckedNodes[0].keys)
      },
      openHandler() {
        this.defaultExpandedKeys = []
        this.defaultValue(this.value)
        this.$emit('open');
      },
      closeHandler() {
        this.$emit('close');
      },
      /**
       * 数据默认回填
       * @param val
       */
      defaultValue(val) {
        this.$nextTick(() => {
          if (this.data[0]) {
            this.defaultExpandedKeys = this.data[0][this.nodeKey] ? [this.data[0][this.nodeKey]] : []
          }
          let setCK = []
          val.map(r => {
            if (r instanceof Object) {
              setCK.push(r[this.nodeKey])
            } else {
              setCK.push(r)
            }
          })
          if (this.multiSelect) {
            this.$refs.tree.setCheckedKeys(setCK)
          } else {
            this.$refs.tree.setCurrentKey(setCK[0])
          }
          // this.defaultExpandedKeys = setCK
        })
      }
    },
    mounted() {
    }
  };
</script>

<style scoped>

</style>
